﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Reflection;
using _CUSTOM_CONTROLS._ChatListBox;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using SoftwareManager;
using System.Net;

namespace WindowsFormsForControlTest
{

    public partial class Form1 : Form
    {
        #region EverythingDllImport
        const int EVERYTHING_OK	= 0;
		const int EVERYTHING_ERROR_MEMORY = 1;
		const int EVERYTHING_ERROR_IPC = 2;
		const int EVERYTHING_ERROR_REGISTERCLASSEX = 3;
		const int EVERYTHING_ERROR_CREATEWINDOW = 4;
		const int EVERYTHING_ERROR_CREATETHREAD = 5;
		const int EVERYTHING_ERROR_INVALIDINDEX = 6;
		const int EVERYTHING_ERROR_INVALIDCALL = 7;

        [DllImport("Everything32.dll", CharSet = CharSet.Unicode)]
		public static extern int Everything_SetSearchW(string lpSearchString);
		[DllImport("Everything32.dll")]
		public static extern void Everything_SetMatchPath(bool bEnable);
		[DllImport("Everything32.dll")]
		public static extern void Everything_SetMatchCase(bool bEnable);
		[DllImport("Everything32.dll")]
		public static extern void Everything_SetMatchWholeWord(bool bEnable);
		[DllImport("Everything32.dll")]
		public static extern void Everything_SetRegex(bool bEnable);
		[DllImport("Everything32.dll")]
		public static extern void Everything_SetMax(int dwMax);
		[DllImport("Everything32.dll")]
		public static extern void Everything_SetOffset(int dwOffset);

		[DllImport("Everything32.dll")]
		public static extern bool Everything_GetMatchPath();
		[DllImport("Everything32.dll")]
		public static extern bool Everything_GetMatchCase();
		[DllImport("Everything32.dll")]
		public static extern bool Everything_GetMatchWholeWord();
		[DllImport("Everything32.dll")]
		public static extern bool Everything_GetRegex();
		[DllImport("Everything32.dll")]
		public static extern UInt32 Everything_GetMax();
		[DllImport("Everything32.dll")]
		public static extern UInt32 Everything_GetOffset();
		[DllImport("Everything32.dll")]
		public static extern string Everything_GetSearchW();
		[DllImport("Everything32.dll")]
		public static extern int Everything_GetLastError();

		[DllImport("Everything32.dll")]
		public static extern bool Everything_QueryW(bool bWait);

		[DllImport("Everything32.dll")]
		public static extern void Everything_SortResultsByPath();

		[DllImport("Everything32.dll")]
		public static extern int Everything_GetNumFileResults();
		[DllImport("Everything32.dll")]
		public static extern int Everything_GetNumFolderResults();
		[DllImport("Everything32.dll")]
		public static extern int Everything_GetNumResults();
		[DllImport("Everything32.dll")]
		public static extern int Everything_GetTotFileResults();
		[DllImport("Everything32.dll")]
		public static extern int Everything_GetTotFolderResults();
		[DllImport("Everything32.dll")]
		public static extern int Everything_GetTotResults();
		[DllImport("Everything32.dll")]
		public static extern bool Everything_IsVolumeResult(int nIndex);
		[DllImport("Everything32.dll")]
		public static extern bool Everything_IsFolderResult(int nIndex);
		[DllImport("Everything32.dll")]
		public static extern bool Everything_IsFileResult(int nIndex);
        [DllImport("Everything32.dll", CharSet = CharSet.Unicode)]
        public static extern void Everything_GetResultFullPathNameW(int nIndex, StringBuilder lpString, int nMaxCount);
		[DllImport("Everything32.dll")]
		public static extern void Everything_Reset();
        #endregion

        ToolTip toolTip = new ToolTip();

        public Form1() {

            InitializeComponent();

        }


        /// <summary>
        /// 绘图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e) {
            chatListBox1.Items.Clear();
            Random rnd = new Random();

            Dictionary<string, List<AppInfo>> AppInfoGroups = DataManager._Instance.AppInfoGroups;

            try
            {
                foreach (string groupName in AppInfoGroups.Keys)
                {
                    ChatListItem item = new ChatListItem(groupName);
                    foreach (AppInfo appInfo in AppInfoGroups[groupName])
                    {
                        ChatListSubItem subItem = new ChatListSubItem(appInfo.CustomAppName, appInfo.CustomAppName, "");
                        if (!File.Exists("Images/" + appInfo.CustomAppName + ".png"))
                            subItem.HeadImage = Image.FromFile("Images/default.png");
                        else
                            subItem.HeadImage = Image.FromFile("Images/" + appInfo.CustomAppName + ".png");
                        item.SubItems.AddAccordingToStatus(subItem);
                    }
                    item.SubItems.Sort();
                    chatListBox1.Items.Add(item);
                }
            }
            catch(Exception exception)
            {
                MessageBox.Show(exception.Message);
                return;
            }
            
        }

        #region Event
        private void chatListBox1_MouseEnterHead(object sender, ChatListEventArgs e)
        {
            if (e.SelectSubItem == null || e.SelectSubItem.NicName == "") { Console.WriteLine("select SubItem is null!"); return;  }

            string nickName = e.SelectSubItem.NicName;
            AppInfo inf = DataManager._Instance.AppSearch(nickName);
            ShowTooltip(toolTip, inf.Tips, 0, 0);
        }

        private void chatListBox1_MouseLeaveHead(object sender, ChatListEventArgs e)
        {
            
        }

        private void chatListBox1_DoubleClickSubItem(object sender, ChatListEventArgs e)
        {

            string CustomAppName = e.SelectSubItem.NicName;
            AppInfo info = DataManager._Instance.AppSearch(CustomAppName);

            if (info == null || info.FullPath == "") return;
            if (!File.Exists(info.FullPath)) { MessageBox.Show("改程序指定的路径不存在！"); return; };

            Process.Start(info.FullPath);
        }

        private void 刷新列表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //调用everything sdk自动创建路径
            if (!File.Exists("Everything.exe")) { MessageBox.Show("Everything.exe没有找到！"); return; }

            Process.Start("Everything.exe");

            Thread.Sleep(2000);

            int i;
            const int bufsize = 260;
            StringBuilder buf = new StringBuilder(bufsize);

            Everything_SetSearchW(".exe");
            Everything_QueryW(true);

            //不断查询结果，直到查到的结果总数不变，即everything已经扫描完了所有的路径
            int lastResultsCount = 0;
            int resultsCount = -1;
            resultsCount = Everything_GetNumResults();

            while (lastResultsCount != resultsCount)
            {
                lastResultsCount = resultsCount;
                Thread.Sleep(500);
                Everything_SetSearchW(".exe");
                Everything_QueryW(true);
                resultsCount = Everything_GetNumResults();
            }

            if (File.Exists("fullPath.txt"))
                File.Delete("fullPath.txt");

            FileStream fs = new FileStream("fullPath.txt", FileMode.Create, FileAccess.Write);//创建写入文件 ;
            StreamWriter sw = new StreamWriter(fs);
            try
            {
                //将路径写入文本
                for (i = 0; i < Everything_GetNumResults(); i++)
                {
                    Everything_GetResultFullPathNameW(i, buf, bufsize);

                    sw.WriteLine(buf.ToString());//开始写入值
                }

                sw.Close();
                fs.Close();
            }
            catch(Exception exc) {
                MessageBox.Show("路径文件写入错误！" + exc.ToString());
                sw.Close();
                fs.Close();
                return;
            }
            

            //自动对路径进行解析
            Process.Start("PathTransfer.exe");

            Application.Exit();

            ////解析完毕
            //DialogResult result = MessageBox.Show("列表刷新完成,点击确认重启程序并刷新列表");
            //if (result == System.Windows.Forms.DialogResult.OK)
            //    Application.Restart();
        }
        private void 搜索ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Finder finder = new Finder();
            finder.Show();
        }
        #endregion

        #region Misc
        public void ShowTooltip(ToolTip tip, string message, int xoffset, int yoffset)
        {
            Point _mousePoint = Control.MousePosition;
            int _x = this.PointToClient(_mousePoint).X;
            int _y = this.PointToClient(_mousePoint).Y;
            tip.Show(message, this, _x + xoffset, _y + yoffset);
            tip.Active = true;
        }


        #endregion

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {

        }

        private void chatListBox1_KeyDown(object sender, KeyEventArgs e)
        {
            
        }

        private void 打开对应文件夹ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            ChatListSubItem currentSelectItem = chatListBox1.SelectSubItem;
            if (currentSelectItem == null) { MessageBox.Show("当前未选中任何Item"); return; }

            string CustomAppName = currentSelectItem.NicName;
            AppInfo info = DataManager._Instance.AppSearch(CustomAppName);

            if (info == null || info.FullPath == "") return;

            string folderName = Path.GetDirectoryName(info.FullPath);
            if (!Directory.Exists(folderName)) { MessageBox.Show(string.Format("{0}指定的路径不存在",folderName)); return; }

            Process.Start(folderName);
        }

        private void 打开本软件目录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start(Application.StartupPath);
        }

        private void 在桌面上建立快捷方式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ChatListSubItem currentSelectItem = chatListBox1.SelectSubItem;
            if (currentSelectItem == null) { MessageBox.Show("当前未选中任何Item"); return; }

            string CustomAppName = currentSelectItem.NicName;
            AppInfo info = DataManager._Instance.AppSearch(CustomAppName);

            if (info == null || info.FullPath == "") return;
            MyUtils.CreateShortcutOnDesktop(CustomAppName, info.FullPath);
        }

        private void 打开特殊路径列表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string fullpath = Application.StartupPath + "/" + Constant.PathHelperFilename;
            Process p = Process.Start(fullpath);
        }
    }
}
